home *** CD-ROM | disk | FTP | other *** search
- Path: cymbal.aix.calpoly.edu!not-for-mail
- From: dstubbs@cymbal.aix.calpoly.edu (Dan Stubbs)
- Newsgroups: comp.lang.c
- Subject: Re: Fastest way to computer log(base2) of x?
- Date: 24 Jan 1996 18:17:33 -0800
- Organization: California Polytechnic State University, San Luis Obispo
- Message-ID: <4e6p7t$1n72@cymbal.aix.calpoly.edu>
- References: <4e61iu$p6e@villa.fc.net>
- NNTP-Posting-User: dstubbs@cymbal.aix.calpoly.edu
-
- In article <4e61iu$p6e@villa.fc.net>,
- Avinash Chopde <avinash@paranoia.com> wrote:
- >[And no, this is not for a homework exercise.]
- >
- >I am trying to find out what could be the fastest way to compute
- >the position of the highest bit in any given integer -- basically, the
- >logarithm to the base 2 of any number.
- >
- >Simplistically, one could do :
- >logbase2(int x)
- >{
- > if (IS_SET_BIT_31(x)) return 31;
- > if (IS_SET_BIT_30(x)) return 30;
- > etc.
- >}
- >
- >An improvement would be to check for BITS_31_16 and BITS_15_0 at first, and
- >then check for BITS_31_24, and BITS_23_16, etc .. (divide problem in half
- >at each stage).
- >
- >Any thoughts or other ideas?
- >
- >Thanks!
- >
- >Avinash Chopde
- >e-mail: avinash@acm.org
- >home page: http://www.paranoia.com/~avinash/
-
- It seems like an interesting exercise to find the left bit using
- a binary search since moving an appropriate mask around (for
- speed) is a bit "different." The following is for 32 bit ints,
- as you can see it is simple to modify for any width int that is
- a power of 2.
-
- /*------------------------------------------------------------------*/
- int left_most_bit (int k) {
- /*
- * returns the position of the left most bit in k assuming that
- * k != 0 and 32 bit ints. The algorithm used is essentially a
- * binary search.
- */
- int posn = 0, width = 16, mask = 0xffff0000;
-
- while (width > 1) {
- if (k & mask) {
- width /= 2;
- mask <<= (posn + width);
- mask >>= posn;
- }
- else {
- mask >>= width;
- posn += width;
- }
- }
- if (k & mask) return posn;
- else return posn+1;
- }
- /*------------------------------------------------------------------*/
-